<?php
namespace app\common\service;

use app\common\helper\ExcelHelper;
use app\common\helper\WeixinHelper;
use app\common\helper\WeixinPaymentHelper;
use app\common\util\Util;
use think\Db;
use think\Model;

class OrderService extends BaseService
{

    /**
     * 后台: 获取订单列表
     * @param $sid
     * @param $type
     * @param $search
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function getOrderAllList($sid, $type, $search, $p, $pageSize){
        $where = [
            'o.sid' => $sid
        ];
        if($search){
            $where['c.name|s.name|s.phone'] = ["like", "%$search%"];
        }

        if($type == 1){
            //全部
            $where['o.status'] = ['<>', -1];
        } elseif($type == 2){
            //待付款
            $where['o.status'] = 0;
        } elseif($type == 3){
            //已付款
            $where['o.status'] = 1;
        } elseif($type == 4){
            //已关闭
            $where['o.status'] = 3;
        }

        $field = 'o.order_id,o.buyer_id,o.order_sn,o.add_time,o.status,o.order_amount,o.buy_type,cp.coupon_name,cp.coupon_price,c.name as course_name,s.name,s.phone,u.user_nickname';
        $group = 'o.order_id,o.buyer_id,o.order_sn,o.add_time,o.status,o.order_amount,o.buy_type,cp.coupon_name,cp.coupon_price,c.name,s.name,s.phone,u.user_nickname';

        $list = db('order o')
                ->join('order_course oc', 'o.order_id=oc.order_id')
                ->join('course c', 'c.courseid=oc.course_id')
                ->join('user u', 'u.user_id=o.buyer_id')
                ->join('students s', 'o.buyer_id=s.uid')
                ->join('coupon cp', 'o.coupon_id=cp.coupon_id', 'LEFT')
                ->field($field)
                ->where($where)
                ->order('o.order_id DESC')
                ->group($group)
                ->limit(($p - 1)*$pageSize, $pageSize)
                ->select();
        if($list){
            foreach($list as $k => $v){
                $list[$k]['add_time'] = date('Y-m-d H:i:s', $v['add_time']);

                $list[$k]['phone'] = Util::hidestr($v['phone'],3,4);
            }
        }

        $count = db('order o')
                ->join('order_course oc', 'o.order_id=oc.order_id')
                ->join('course c', 'c.courseid=oc.course_id')
                ->join('user u', 'u.user_id=o.buyer_id')
                ->join('students s', 'o.buyer_id=s.uid')
                ->join('coupon cp', 'o.coupon_id=cp.coupon_id', 'LEFT')
                ->where($where)
                ->group($group)
            ->count();
        $data = [
            'page' => [
                'count' => $count
            ],
            'content' => $list
        ];
        return $data;
    }


    /**
     * 后台: 导出订单列表
     * @param $sid
     * @param $type
     * @param $begin
     * @param $end
     * @return array
     */
    public function exportOrderList($sid, $type, $begin, $end){
        $begin_time = strtotime($begin);
        $end_time = strtotime($end);
        $field = 'o.buyer_id,o.order_sn,o.order_amount,o.total_fee,o.buy_type,o.add_time,o.status,c.name as course_name,s.name,s.phone,ui.parent_id';
        $group = 'o.order_id,o.buyer_id,o.order_sn,o.order_amount,o.total_fee,o.buy_type,o.add_time,c.name,s.name,s.phone,ui.parent_id';
        $where = [
            'o.sid' => $sid,
            'o.add_time' => ['between', [$begin_time, $end_time]]
        ];
        if($type == 1){
            //全部
            $where['o.status'] = ['<>', -1];
        } elseif($type == 2){
            //待付款
            $where['o.status'] = 0;
        } elseif($type == 3){
            //已付款
            $where['o.status'] = 1;
        } elseif($type == 4){
            //已取消
            $where['o.status'] = 3;
        }

        $list = db('order o')
                ->join('order_course oc', 'o.order_id=oc.order_id')
                ->join('course c', 'oc.course_id=c.courseid')
                ->join('students s', 's.uid=o.buyer_id', 'LEFT')
                ->join('user_integral ui', 'ui.userid=o.buyer_id', 'LEFT')
                ->field($field)
                ->where($where)
                ->order('o.add_time DESC')
                ->group($group)
                ->select();

        $down_array[1] = [
            'A1' => '订单类型',
            'B1' => '课程名称',
            'C1' => '订单编号',
            'D1' => '下单时间',
            'E1' => '购买人姓名',
            'F1' => '购买人手机号',
            'G1' => '顾问姓名',
            'H1' => '订单总金额',
            'I1' => '订单实付金额',
            'J1' => '订单状态'
        ];
        foreach($list as $k => $v){
            //获取顾问名称
            $counselor_name = db('user')->where(['user_id' => $v['parent_id']])->value('user_name');

            $order_status = '';
            if($v['status'] == 0){
                $order_status = '待付款';
            } elseif($v['status'] == 1){
                $order_status = '已支付';
            } elseif($v['status'] == 2){
                $order_status = '已支付';
            } elseif($v['status'] == 3){
                $order_status = '已关闭';
            } elseif($v['status'] == 5){
                $order_status = '线下支付待确认';
            } elseif($v['status'] == 6){
                $order_status = '线下支付已拒绝';
            }

            $key = $k+2;
            $down_array[$key] = [
                'A'.$key => $v['buy_type'] == 1 ? '微信支付' : '后台操作',
                'B'.$key => $v['course_name'],
                'C'.$key => $v['order_sn'],
                'D'.$key => date('Y-m-d H:i:s', $v['add_time']),
                'E'.$key => $v['name'],
                'F'.$key => $v['phone'],
                'G'.$key => $counselor_name,
                'H'.$key => $v['order_amount'],
                'I'.$key => $v['total_fee'],
                'J'.$key => $order_status
            ];
        }
        $filename = date('YmdHis',time()).'订单列表.xlsx';
        ExcelHelper::down($filename, $down_array, 'orderList');
        return ['status' =>1, 'msg' => '导出成功'];
    }

    /**
     * 后台: 管理员确认付款操作
     * @param $sid
     * @param $order_id
     * @return array
     */
    public function confirmPayByAdmin($sid, $order_id){
        //待支付和线下支付未确认均可
        $order_info = db('order')->where(['sid' => $sid, 'order_id' => $order_id, 'status' => ['in', [0,5]]])->find();
        if(!$order_info){
            return ['status'=> 0, 'msg' => '订单不存在'];
        }
        Db::startTrans();
        try{
            //更改订单状态
            db('order')->where(['sid' => $sid, 'order_id' => $order_id])->update(['status' => 1, 'buy_type' => 2]);
            $order_log = [
                'order_id' => $order_id,
                'order_sn' => $order_info['order_sn'],
                'operator' => 'admin',
                'order_origin_status' => 0,
                'order_change_status' => 1,
                'sid' => $sid,
                'remark' => '后台管理员修改订单状态',
                'log_time' => time()
            ];
            db('order_log')->insert($order_log);
            Db::commit();
            return ['status' => 1, 'msg' => '确认付款成功'];
        } catch(\Exception $e){
            Db::rollback();
            return ['status' => 0, 'msg' => '系统异常，暂时无法操作'];
        }
    }

    /**
     * 后台: 管理员关闭订单
     * @param $sid
     * @param $order_id
     * @return array
     */
    public function closeOrderByAdmin($sid, $order_id){
        $where = [
            'o.sid' => $sid,
            'o.order_id' => $order_id,
            'o.status' => ['in', [0,4,5]] //待付款或冻结支付的订单或线下支付未确认的订单
        ];
        $field = 'o.order_id,o.buyer_id,o.coupon_id,oc.course_id';
        $order_info = db('order o')
                    ->field($field)
                    ->join('order_course oc', 'o.order_id=oc.order_id')
                    ->where($where)
                    ->find();
        if(!$order_info){
            return ['status'=> 0, 'msg' => '订单不存在'];
        }
        //调用取消订单业务逻辑
        $result = $this->cancelOrderLogic($sid, $order_info['buyer_id'], $order_id, $order_info['course_id'], $order_info['coupon_id']);
        return $result;
    }

    /**
     * 微信端: 购买者是否完善身份信息
     * @param $sid
     * @param $uid
     * @return int
     */
    public function buyConfirmIdentity($sid, $uid){
        $active_state = 1;
        $students_id = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('students_id');
        if(!$students_id){
            $active_state = 0;
        }
       /* $student = db('students')->field('name,phone,company')->where(['id' => $students_id])->find();

        if($student['phone']){
            if(empty($student['name']) || empty($student['company'])){
                //手机激活 而其他资料未激活的状态
                $active_state = 2;
            }
            $company = Util::unserializeStr($student['company']);
            if(empty($company[0]['cname']) || empty($company[0]['position'])){
                $active_state = 2;
            }
        } else {
            $active_state = 0;
        }

        if(empty($student['name']) || empty($student['phone']) || empty($student['company'])){
            $active_state = 0;
        }*/

//        $company = Util::unserializeStr($student['company']);
//        if(empty($company[0]['cname']) || empty($company[0]['position'])){
//            $active_state = 0;
//        }
        return $active_state;
    }


    /**
     * 微信端: 获取用户订单列表
     * @param $sid
     * @param $uid
     * @param int $type
     * @param $p
     * @param $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getUserOrderList($sid, $uid, $type = 1, $p, $pageSize){
        $field = 'c.name,c.speaker,c.schooltime,c.pic,c.course_price,o.order_id,o.status,oc.course_id';
        $where = [
            'oc.sid' => $sid,
            'oc.buyer_id' => $uid,
            'c.course_status' => ['<>', -1]
        ];

        if($type == 1){
            //全部订单
            $where['o.status'] = ['<>', -1];
        } elseif($type == 2){
            //待付款
            $where['o.status'] = 0;
        } elseif($type == 3){
            //已付款
            $where['o.status'] = 1;
        } elseif($type == 4){
            //待确认
            $where['o.status'] = 5;
        }

        $list = db('order_course oc')
                ->join('order o', 'o.order_id=oc.order_id')
                ->join('course c', 'oc.course_id=c.courseid')
                ->field($field)
                ->where($where)
                ->order('o.add_time DESC')
                ->limit(($p - 1)*$pageSize, $pageSize)
                ->select();
        if($list){
            foreach ($list as $k => $v) {
                $list[$k]['schooltime'] = date('Y-m-d H:i:s', $v['schooltime']);
                $list[$k]['speaker'] = json_decode($v['speaker'], 1);
            }
        }
        return $list;
    }

    /**
     * 微信端: 确认下单
     * @param $sid
     * @param $uid
     * @param $postParam
     * @return array
     */
    public function confirmBuy($sid, $uid, $postParam){
        $course_id = $postParam['course_id']; //保存课程ID
        $coupon_id = $postParam['coupon_id']; //保存优惠券ID
        $payment_type = $postParam['payment_type']; //保存支付方式

        //是否重复下单
        $is_repeat_order = $this->_isRepeatOrder($sid, $uid, $course_id);
        if($is_repeat_order){
            return ['status' => 0, 'msg' => '该课程不能重复购买'];
        }

        //校验该课程是否可以购买
        $course_valid = $this->_isValidCourse($course_id);
        if($course_valid['status'] == 0){
            return $course_valid;
        }
        $course_info = $course_valid['data'];

        //判断支付方式
        if($course_info['payment_type']){
            $allow_payment_type = explode(',', $course_info['payment_type']);
            if(!in_array($payment_type, $allow_payment_type)){
                return ['status' => 0, 'msg' => '支付方式错误'];
            }
        }

        //是否使用优惠券
        $coupon_info = []; //保存优惠券信息
        if($coupon_id){
            $coupon_valid = $this->_isValidCoupon($uid, $coupon_id, $course_id);
            //优惠券验证失败
            if($coupon_valid['status'] == 0){
                return $coupon_valid;
            }
            $coupon_info = $coupon_valid['data'];
        }

        //验证支付金额合法性
        $payment_amount_valid = $this->_isValidPaymentAmount($postParam['payment_amount'], $course_info, $coupon_info);
        if($payment_amount_valid['status'] == 0){
            return $payment_amount_valid;
        }

        //保存是否免支付、实际支付金额
        list($free_pay, $fact_payment_amount) = $payment_amount_valid['data'];
        $order_amount = $course_info['course_price']; //订单金额为课程价格

        if($payment_type == 1){
            // --------------------------------线上支付---------------------------------

            if($free_pay == true){
                //免支付
                $result = $this->_freePayment($sid, $uid, $course_id, $coupon_id);
                if($result['status'] == 0){
                    return $result;
                } else {
                    //跳转成功页面
                    $order_info = $result['data'];
                    $order_info['course_name'] = $course_info['name'];
                    $order_info['course_id'] = $course_id;

                    //发送下单成功模版消息提醒
                    $wxTplMsgService = new WxTplMsgService();
                    $wxTplMsgService->send($sid, $uid, 'payment_success', $order_info);

                    $successUrl = $this->domain.'/m/html/dmscommon.html?sid='.$sid.'&uid='.$uid.'&escape=main.buySuccess';;
                    $data = [
                        'status' => 1,
                        'data' => $order_info,
                        'url' => $successUrl
                    ];
                    return $data;
                }
            } else {
                $result = $this->_addOrder($sid, $uid, $course_id, $coupon_id, $fact_payment_amount, $order_amount, 1);
                if($result['status'] == 0){
                    return $result;
                } else {
                    $order_info = $result['data'];
                    $order_info['course_name'] = $course_info['name'];
                    //跳转微信支付页面
                    $paymentUrl = WeixinPaymentHelper::getPaymentSiteUrl($sid, $order_info['order_id']);
                    $data = [
                        'status' => 2,
                        'data' => $order_info,
                        'url' => $paymentUrl
                    ];
                    return $data;
                }
            }
        } elseif ($payment_type == 2){
            // --------------------------------线下支付---------------------------------
            //生成订单
            $result = $this->_addOrder($sid, $uid, $course_id, $coupon_id, $fact_payment_amount, $order_amount, 3);
            if($result['status'] == 0){
                return $result;
            } else {
                $order_info = $result['data'];

                //给上级顾问或管理员推送确认线下付款的模版消息
                $wxTplMsgService = new WxTplMsgService();
                $course_info['order_id'] = $order_info['order_id'];
                $wxTplMsgService->send($sid, $uid, 'offline_payment_apply', $course_info);

                $offlinePaymentUrl = $this->domain.'/m/html/dmscommon.html?sid='.$sid.'&uid='.$uid.'&escape=main.offlineSuccess';;
                $data = [
                    'status' => 3,
                    'data' => $order_info,
                    'url' => $offlinePaymentUrl
                ];
                return $data;
            }
        }
        exit();
    }

    /**
     * 下单: 生成订单
     * @param $sid
     * @param $uid
     * @param $course_id
     * @param int $coupon_id
     * @param $payment_amout
     * @param $order_amount
     * @return array
     */
    private function _addOrder($sid, $uid, $course_id, $coupon_id, $payment_amout, $order_amount, $buy_type){
        $order = [
            'order_sn' => Util::makeOrderSn($uid),
            'sid' => $sid,
            'buyer_id' => $uid,
            'add_time' => time(),
            'order_amount' => $order_amount, //订单金额
            'payment_amount' => $payment_amout, //实际需要支付的金额
            'coupon_id' => $coupon_id,
            'buy_type' => $buy_type, //购买方式
            'is_free_pay' => 0,
            'status' => $buy_type == 3 ? 5 : 0 //buy_type=3时，为线下支付，状态5代表待管理员确认
        ];
        $result = $this->_addOrderLogic($sid, $uid, $course_id, $coupon_id, $order, false);
        if($result['status'] == 0){
            return $result;
        } else {
            $order['order_id'] = $result['data'];
            $result['data'] = $order;
            return $result;
        }
    }

    /**
     * 下单: 是否重复下单
     * @param $sid
     * @param $uid
     * @param $course_id
     * @return bool
     */
    private function _isRepeatOrder($sid, $uid, $course_id){
        $where = [
            'oc.sid' => $sid,
            'oc.buyer_id' => $uid,
            'oc.course_id' => $course_id,
            'o.status' => ['in', [0,1,5]] //订单状态为未支付、支付完成、线下支付待确认
        ];
        $result = db('order_course oc')
            ->join('order o', 'oc.order_id=o.order_id')
            ->where($where)
            ->find();
        return $result ? true : false;
    }

    /**
     * 下单: 免支付
     * @param $sid
     * @param $uid
     * @param $course_id
     * @param int $coupon_id
     * @return array
     */
    private function _freePayment($sid, $uid, $course_id, $coupon_id = 0){
        $order = [
            'order_sn' => Util::makeOrderSn($uid),
            'sid' => $sid,
            'buyer_id' => $uid,
            'add_time' => time(),
            'total_fee' => 0,
            'pay_time' => time(),
            'order_amount' => 0,
            'payment_amount' => 0,
            'coupon_id' => $coupon_id,
            'buy_type' => 1,
            'is_free_pay' => 1,
            'status' => 1 //已支付
        ];
        $result = $this->_addOrderLogic($sid, $uid, $course_id, $coupon_id, $order, true);
        if($result['status'] == 0){
            return $result;
        } else {
            $order['order_id'] = $result['data'];
            $result['data'] = $order;
            return $result;
        }
    }

    /**
     * 下单: 下单业务逻辑
     * @param $sid
     * @param $uid
     * @param $course_id
     * @param $coupon_id
     * @param array $order
     * @return array
     */
    private function _addOrderLogic($sid, $uid, $course_id, $coupon_id, $order = [], $is_free_pay = false){
        Db::startTrans();
        try{
            //生成订单
            $order_id = db('order')->insertGetId($order);

            //生成订单课程
            $order_course = [
                'order_id' => $order_id,
                'course_id' => $course_id,
                'sid' => $sid,
                'buyer_id' => $uid
            ];
            db('order_course')->insert($order_course);

            //减少课程席位
            db('course')->where(['courseid' => $course_id])->setDec('stock', 1);

            //使用优惠券的情况
            if($coupon_id){
                //已使用 +1
                db('coupon')->where(['coupon_id' => $coupon_id])->setInc('use_num',1);
                //更改优惠券使用状态
                db('user_coupon')->where(['sid' => $sid, 'uid' => $uid, 'coupon_id' => $coupon_id])->update(['use_time' => time(), 'status' => 1]);
            }

            if($is_free_pay){
                //免支付写入动态
                $course_name = db('course')->where(['courseid' => $course_id])->value('name');
                $track_msg = '购买了《'.$course_name.'》课程';
                TrackService::write($track_msg, $sid, $uid);
            }

            Db::commit();
            return ['status' => 1, 'msg' => '下单成功', 'data' => $order_id];
        } catch(\Exception $e){
            Db::rollback();
            return ['status' => 0, 'msg' => '系统异常，请联系管理员'];
        }
    }


    /**
     * 下单: 校验支付金额合法性
     * @param $post_payment_amount
     * @param array $course_info
     * @param array $coupon_info
     * @return array
     */
    private function _isValidPaymentAmount($post_payment_amount, $course_info = [], $coupon_info = []){
        $post_payment_amount = (float)number_format($post_payment_amount, 2, '.', ''); //提交上来的支付金额
        $course_price = (float)number_format($course_info['course_price'], 2, '.', ''); //课程价格
        $coupon_price = $coupon_info ? (float)number_format($coupon_info['coupon_price'], 2, '.', '') : 0; //优惠券面额

        if($post_payment_amount == 0){
            //免支付
            $free_pay = true;
            if($course_price == 0){
                //课程价格为0，则为免费
                return ['status' => 1, 'msg' => '免费课程', 'data' => [$free_pay,0]];
            } else {
                if($coupon_price >= $course_price){
                    //优惠券完全抵扣课程价格的情况
                    return ['status' => 1, 'msg' => '优惠券完全抵扣课程价格', 'data' => [$free_pay,0]];
                } else {
                    return ['status' => 0, 'msg' => '支付金额错误，下单失败'];
                }
            }
        } else {
            //需要支付
            $free_pay = false;
            $fact_payment_amount = $course_price - $coupon_price;
            $fact_payment_amount = (float)number_format($fact_payment_amount, 2, '.', '');

            if($fact_payment_amount - $post_payment_amount != 0){
                return ['status' => 0, 'msg' => '支付金额错误，下单失败！'];
            } else {
                return [
                    'status' => 1,
                    'msg' => '实付金额校验通过',
                    'data' => [$free_pay, $fact_payment_amount]
                ];
            }
        }
    }

    /**
     * 下单: 校验课程合法性
     * @param $course_id
     * @return array|false|\PDOStatement|string|Model
     */
    private function _isValidCourse($course_id){
        $where = [
            'courseid' => $course_id,
            'schoolovertime' => ['>', time()], //课程结束时间之前
            'is_allow_buy' => 1,
//            'stock' => ['>', 0],
            'course_status' => 1
        ];
        $course = db('course')->where($where)->find();
        if(!$course){
            return ['status' => 0, 'msg' => '当前课程不支持购买'];
        }
        if($course['stock'] == 0){
            return ['status' => 0, 'msg' => '当前课程已售罄'];
        }
        $data = [
            'data' => $course,
            'status' => 1,
            'msg' => '课程可购买'
        ];
        return $data;
    }

    /**
     * 下单: 校验优惠券合法性
     * @param $uid
     * @param $coupon_id
     * @param $course_id
     * @return array
     */
    private function _isValidCoupon($uid, $coupon_id, $course_id){
        $where = [
            'uc.coupon_id' => $coupon_id,
            'uc.uid' => $uid,
            'uc.status' => 0,
            'c.coupon_begin' => ['<', time()],
            'c.coupon_end' => ['>', time()],
            'c.status' => ['<>', -1]
        ];
        $field = 'c.coupon_id,c.coupon_name,c.coupon_price,c.coupon_begin,c.coupon_end,c.coupon_type,c.receive_classid';
        $coupon_info =  db('user_coupon uc')
                        ->join('coupon c', 'uc.coupon_id=c.coupon_id')
                        ->field($field)
                        ->where($where)
                        ->find();
        if(empty($coupon_info)){
            return ['status' => 0, 'msg' => '优惠券信息有误，下单失败'];
        }

        //专属券
        if($coupon_info['coupon_type'] == 2){
            //查询该课程绑定的班级
            $course_class = db('course_class')->where(['courseid' => $course_id])->select();
            $class_ids = [];
            if($course_class){
                foreach($course_class as $key => $val){
                    $class_ids[$key] = $val['classid'];
                }
            }

            //限制使用的班级ID
            $receive_classid = explode(',', $coupon_info['receive_classid']);

            //求交集
            if(!array_intersect($receive_classid, $class_ids)){
                return ['status' => 0, 'msg' => '无该优惠券使用权,下单失败'];
            }
        }

        $data = [
            'status' => 1,
            'msg' => '验证优惠券通过',
            'data' => $coupon_info
        ];
        return $data;
    }


    public function cancelOrderByUser($sid, $uid, $order_id){
        $where = [
            'oc.sid' => $sid,
            'oc.buyer_id' => $uid,
            'oc.order_id' => $order_id,
            'o.status' => ['in', [0,5]] //未支付的订单、线下支付待确认的订单
        ];
        $field = 'o.*,oc.course_id';
        $info = db('order_course oc')
                ->join('order o', 'o.order_id=oc.order_id')
                ->field($field)
                ->where($where)
                ->find();
        if(!$info){
            return ['status' => 0, 'msg' => '不存在此订单'];
        }

        return $this->cancelOrderLogic($sid, $uid, $order_id, $info['course_id'], $info['coupon_id']);
    }

    /**
     * 取消订单业务逻辑
     * @param $sid
     * @param $uid
     * @param $order_id
     * @param $course_id
     * @param $coupon_id
     * @return array
     */
    public function cancelOrderLogic($sid, $uid, $order_id, $course_id, $coupon_id){
        Db::startTrans();
        try{
            //更改订单状态
            db('order')->where(['order_id' => $order_id, 'sid' => $sid])->setField('status', 3);

            //退回课程席位
            db('course')->where(['courseid' => $course_id])->setInc('stock', 1);

            //使用优惠券的情况
            if($coupon_id){
                //已使用 -1
                db('coupon')->where(['coupon_id' => $coupon_id])->setDec('use_num', 1);
                //更改优惠券使用状态
                db('user_coupon')->where(['sid' => $sid, 'uid' => $uid, 'coupon_id' => $coupon_id])->setField('status', 0);
            }
            Db::commit();
            return ['status' => 1, 'msg' => '取消订单成功'];
        } catch(\Exception $e){
            Db::rollback();
            return ['status' => 0, 'msg' => '系统异常，请联系管理员'];
        }
    }

    /**
     * 获取订单详情
     * @param $sid
     * @param $order_id
     * @return array
     */
    public function getOrderDetail($sid, $order_id){
        $field = 'o.order_id,o.order_amount,o.payment_amount,o.status,c.name as course_name,c.course_price,c.schooltime,c.schoolovertime,c.speaker,
        c.course_status as course_status,s.name as students_name,s.phone,cp.coupon_price';
        $where = [
            'o.sid' => $sid,
            'o.order_id' => $order_id,
            'o.status' => ['<>', -1]
        ];
        $info = db('order o')
                ->field($field)
                ->join('order_course oc', 'o.order_id=oc.order_id')
                ->join('course c', 'oc.course_id=c.courseid')
                ->join('students s', 'o.buyer_id=s.uid')
                ->join('coupon cp', 'o.coupon_id=cp.coupon_id', 'LEFT')
                ->where($where)
                ->find();
        if($info){
            $info['speaker'] = json_decode($info['speaker'], 1);
            $info['schooltime_date'] = date('Y/m/d', $info['schooltime']);
            $info['schooltime_str'] = date('H:i', $info['schooltime']);
            $info['schoolovertime_str'] = date('H:i', $info['schoolovertime']);
            $info['coupon_price'] = $info['coupon_price'] ?? 0;
            return ['status' => 1, 'msg' => '获取成功', 'data' => $info];
        } else {
            return ['status' => 0, 'msg' => '不存在此订单'];
        }
    }


    /**
     * 线下支付确认操作
     * @param $sid
     * @param $uid
     * @param $order_id
     * @param $operate_status
     * @return array
     */
    public function offlineOrderConfirm($sid, $uid, $order_id, $operate_status){
        $field = 'o.order_id,o.order_sn,o.buyer_id,o.order_amount,o.coupon_id,oc.course_id';
        $order = db('order o')
                ->field($field)
                ->join('order_course oc', 'o.order_id=oc.order_id')
                ->where([
                    'o.order_id' => $order_id,
                    'o.status' => 5
                ])
            ->find();
        if(!$order){
            return ['status' => 0, 'msg' => '订单信息有误'];
        }

        //判断当前操作人员的权限
        $pid = db('user_integral')->where(['sid' => $sid, 'userid' => $order['buyer_id']])->value('counselor_id');
        if($pid != $uid){
            //判断是否为管理员
            $is_admin = db('user_integral')->where(['userid' => $uid, 'is_administrator' => 1])->find();
            if(!$is_admin){
                return ['status' => 0, 'msg' => '对不起，您无操作权限'];
            }
        }

        Db::startTrans();
        try{
            //更改订单状态
            $order_update = [
                'pay_time' => time(),
                'status' => $operate_status == 1 ? 1 : 6, //同意或是拒绝
            ];
            db('order')->where(['order_id' => $order_id])->update($order_update);
            //插入订单日志
            $log_data = [
                'order_id' => $order_id,
                'order_sn' => $order['order_sn'],
                'operator' => 'admin',
                'order_origin_status' => 5,
                'order_change_status' => $operate_status == 1 ? 1 : 6,
                'sid' => $sid,
                'remark' => '线下支付，顾问或管理员确认',
                'log_time' => time()
            ];
            db('order_log')->insert($log_data);

            $course = db('course')->field('name,schooltime')->where(['courseid' => $order['course_id']])->find();
            $wxTplMsgService = new WxTplMsgService();
            if($operate_status == 1){
                //---------------------通过-----------------
                //写入动态
                $track_msg = '购买了《'.$course['name'].'》课程';
                $trackService = new TrackService();
                $trackService->writeTrackSmall($track_msg, $sid, $order['buyer_id']);
            } else {
                //---------------------拒绝-----------------
                //退回课程席位
                db('course')->where(['courseid' => $order['course_id']])->setInc('stock', 1);

                //使用优惠券的情况
                if($order['coupon_id']){
                    //已使用 -1
                    db('coupon')->where(['coupon_id' => $order['coupon_id']])->setDec('use_num', 1);
                    //更改优惠券使用状态
                    db('user_coupon')->where(['sid' => $sid, 'uid' => $order['buyer_id'], 'coupon_id' => $order['coupon_id']])->setField('status', 0);
                }
            }
            Db::commit();

            //发送模版消息 事务之外
            if($operate_status == 1){
                //给用户发送通过提醒
                $wxTplMsgService->send($sid, $order['buyer_id'], 'offline_payment_pass', $course);
                //给上级或管理员发送下单成功提醒
                $wxTplMsgService->send($sid, $order['buyer_id'], 'payment_success', $order);
            } else {
                //给用户发送拒绝提醒
                $wxTplMsgService->send($sid, $order['buyer_id'], 'offline_payment_refuse', $course);
            }
            return ['status' => 1, 'msg' => '操作成功'];
        }catch(\Exception $e){
            Db::rollback();
            return ['status' => 0, 'msg' => '操作失败'];
        }
    }
}







